package com.nash.demands;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class OrdersActivity extends Activity {
  private ListView list;
  private DemandsActivity app;

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.orders);

    list = (ListView) findViewById(R.id.listView1);
    app = (DemandsActivity) getParent();
    app.orderActivity = this;
    setAdapterOrders();
    list.setFocusableInTouchMode(true);
    list.setOnFocusChangeListener(new View.OnFocusChangeListener() {
      @Override
      public void onFocusChange(View arg0, boolean arg1) {
      }
    });
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> adapterView, View view, int pos, long id) {
        Intent intent = new Intent(OrdersActivity.this, DocHeadActivity.class);
        Bundle b = new Bundle();
        b.putLong("demand_id", id);
        int addit = ((Cursor) (list.getItemAtPosition(pos))).getInt(6);
        b.putInt("addit", addit);
        intent.putExtras(b);
        startActivityForResult(intent, (addit == 0) ? DemandsActivity.EDIT_REQUEST_CODE : DemandsActivity.VIEW_REQUEST_CODE);
      }
    });

    list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
      @Override
      public boolean onItemLongClick(AdapterView<?> adapterView, View view, int pos, long id) {
        if (app.adminMode){
          DemandsActivity.db.execSQL("update " + Helper.TBL_DEMAND + " set addit = (case when (addit=0) then 1 else 0 end) where " + BaseColumns._ID + "=" + id);
          OrdersActivity.this.setAdapterOrders();
          return true;
        }
        //currItemOnContextMenuId = id;
        return false;
      }
    });

  }

  @Override
  public boolean onContextItemSelected(MenuItem item) {
    if (item.getTitle().equals(getResources().getString(R.string.CMenuEditOrder))) {
      // function1(item.getItemId());
    } else {
      return false;
    }
    return true;
  }

  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == DemandsActivity.EDIT_REQUEST_CODE) {
      if (resultCode == RESULT_OK) {
        setAdapterOrders();
      }
    }
  }

  public class SpecialColorsAdapter extends SimpleCursorAdapter {
    private int[] colors = new int[] { 0xff6f1010, 0xff000000 };

    public SpecialColorsAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
      super(context, layout, c, from, to);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      View view = super.getView(position, convertView, parent);
      Cursor c = getCursor();
      // c.moveToPosition(position);
      int addit = c.getInt(6);
      view.setBackgroundColor(colors[addit]);
      return view;
    }
  }

  private final String OrderFields[] = { Helper.TBL_AGENT_NAME, BaseColumns._ID, "summa", Helper.TBL_DEMAND_DATE };
  private final int[] OrderTo = new int[] { R.id.order_agent_name_entry, R.id.order_id_entry, R.id.order_sum_entry };

  public void setAdapterOrders() {

    Calendar c=Calendar.getInstance();
    c.set(app.mYear, app.mMonth, app.mDay);
    Date d=c.getTime();
    final SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
    
    
    StringBuilder sb = new StringBuilder()
        .append(
            "select d." + BaseColumns._ID + ",a." + Helper.TBL_AGENT_NAME + ",d." + Helper.TBL_DEMAND_DATE + ",d." + Helper.TBL_DEMAND_ID_HOST + ",d." + Helper.TBL_DEMAND_ID_OSNR + ",d." + Helper.TBL_DEMAND_INFO + ",d."
                + Helper.TBL_DEMAND_ADDIT + ", round(sum(dl.price*dl.amount),2)||' руб.' as summa"
                + " from " + Helper.TBL_DEMAND + " d," + Helper.TBL_AGENT + " a left join "+Helper.TBL_DEMAND_LINE+" dl on dl."+Helper.TBL_DEMAND_LINE_ID_DEMAND+"=d."+BaseColumns._ID+" where d."
                + Helper.TBL_DEMAND_ID_AGENT + "=a." + BaseColumns._ID + " and d."+Helper.TBL_DEMAND_DEMAND_DATE+"='").append(sdf.format(d))
        .append("'");
    sb.append(" group by d." + BaseColumns._ID + ",a." + Helper.TBL_AGENT_NAME + ",d." + Helper.TBL_DEMAND_DATE + ",d." + Helper.TBL_DEMAND_ID_HOST + ",d." + Helper.TBL_DEMAND_ID_OSNR + ",d." + Helper.TBL_DEMAND_INFO
        + ",d." + Helper.TBL_DEMAND_ADDIT);
    ;
    try {
      Cursor data = DemandsActivity.db.rawQuery(sb.toString(), null);
      data.moveToFirst();
      startManagingCursor(data);
      list.setAdapter(new SpecialColorsAdapter(this, R.layout.order_entry, data, OrderFields, OrderTo));
    } catch (SQLException e) {
      Toast.makeText(this.getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
    }
    
  }

}